import * as tf from "@tensorflow/tfjs";
import * as tfvis from "@tensorflow/tfjs-vis";
import { getData } from "./data";

(async () => {
  let data = getData(400);
  console.log(data);
  console.log([
    data.filter((p) => p.label === 1),
    data.filter((p) => p.label === 0),
  ]);
  tfvis.render.scatterplot(
    { name: "逻辑回归表" },
    {
      values: [
        data.filter((p) => p.label === 1),
        data.filter((p) => p.label === 0),
      ],
    }
  );

  let model = tf.sequential();
  model.add(
    tf.layers.dense({
      units: 1, // 一个输出维度就够了,只有一个神经元,
      inputShape: [2],
      activation: "sigmoid", // 输出值压缩到 0 - 1 之间
    })
  );

  model.compile({
    loss: tf.losses.logLoss,
    // optimizer: tf.train.adam(),
    optimizer: tf.train.sgd(0.1),
  });

  let inputs = tf.tensor(data.map((p) => [p.x, p.y]));

  let output = tf.tensor(data.map((p) => p.label));

  // 获取表单的提交
  window["predict"] = ()=>{
    let formData = document.form;
    let pred =  model.predict(tf.tensor([[formData.x.value * 1,formData.y.value * 1]])); // [ [] ]
    console.log(pred.dataSync()[0]);
    return false;
  }
  await model.fit(inputs, output,{
      batchSize: 40,
      epochs: 50, // 训练50一轮
      callbacks: tfvis.show.fitCallbacks({
          name:"训练过程"
      },["loss"])
  });
  console.log("训练完成");
  
})();
